package org.example.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.common.R;
import org.example.interceptor.UserHolder;
import org.example.mapper.*;
import org.example.pojo.entity.*;
import org.example.pojo.vo.LoginVo;
import org.example.pojo.vo.WmNewsVo;
import org.example.pojo.vo.WmNewsVoPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.service.IWmNewsService;
import org.example.utils.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-26
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private ApCommentMapper commentMapper;

    @Autowired
    private ApLoveMapper apLoveMapper;

    @Autowired
    private ApCommentMapper apCommentMapper;

    @Autowired
    private ApCollectMapper apCollectMapper;

    @Autowired
    private ApUserMapper apUserMapper;


    @Override
    public Page listNews(Integer page, Integer size, String channelId, String title) {

        QueryWrapper<WmNews> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(channelId) && !"-1".equals(channelId)) {
            wrapper.eq("channel_id", channelId);
        } else {
            wrapper.orderByAsc("RAND()");
        }
        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        wrapper.eq("status", 1);

        Page pages = new Page(page, size);
        //获取分页数据
        Page pageData = baseMapper.selectPage(pages, wrapper);

        List<WmNews> records = pageData.getRecords();

        List<WmNewsVoPage> wmNewsVos = new ArrayList<>();
        QueryWrapper<ApComment> commetWrapper = new QueryWrapper<>();
        for (WmNews record : records) {
            WmNewsVoPage wmNewsVo = new WmNewsVoPage();
            BeanUtils.copyProperties(record, wmNewsVo);

            //查询单挑记录的评论数量
            commetWrapper.eq("news_id", record.getId());
            Long count = commentMapper.selectCount(commetWrapper);
            wmNewsVo.setCommentCount(count);
            wmNewsVos.add(wmNewsVo);
        }
        pageData.setRecords(wmNewsVos);

        return pageData;

    }

    @Override
    public WmNewsVo getNewsDetail(Integer newsId, HttpServletRequest request) {
        WmNews newsDetail = wmNewsMapper.getNewsDetail(newsId);
        //查询点赞量，和收藏数量
        Long likeCount = apLoveMapper.selectCount(new QueryWrapper<ApLove>().eq("article_id", newsId));
        Long collectCount = apCollectMapper.selectCount(new QueryWrapper<ApCollect>().eq("article_id", newsId));

        Long countLove = 0L;
        Long countCollect = 0L;
        if (!StringUtils.isEmpty(request.getHeader("token"))) {
            LoginVo loginVo = JWTUtils.parseToken(request.getHeader("token"));

            //查询是否点赞收藏
            QueryWrapper<ApLove> wrapperLove = new QueryWrapper();
            wrapperLove.eq("article_id", newsId);
            wrapperLove.eq("love_user_id", loginVo.getId());
            countLove = apLoveMapper.selectCount(wrapperLove);

            QueryWrapper<ApCollect> wrapperCollect = new QueryWrapper();
            wrapperCollect.eq("article_id", newsId);
            wrapperCollect.eq("collect_user_id", loginVo.getId());
            countCollect = apCollectMapper.selectCount(wrapperCollect);
        }

        //获取用户图片
        ApUser user = apUserMapper.selectById(newsDetail.getUserId().toString());


        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(newsDetail, wmNewsVo);
        wmNewsVo.setLikeCount(likeCount);
        wmNewsVo.setCollectCount(collectCount);
        wmNewsVo.setUserImg(user.getImage());
        if (countLove > 0) {
            wmNewsVo.setIsLike(1);
        }
        if (countCollect > 0) {
            wmNewsVo.setIsCollect(1);
        }
        return wmNewsVo;
    }

    @Override
    public void publish(WmNews wmNews) {
        wmNews.setUserId(UserHolder.getUserId());
        wmNews.setLabels(UserHolder.get().getName());
        wmNews.setStatus(0);
        wmNews.setCreatedTime(new Date());
        baseMapper.insert(wmNews);
    }

    @Override
    public R person(int page, int size, String type, String param) {
        QueryWrapper wrapper = new QueryWrapper<>();
        if ("all".equals(type)) {
            if (!StringUtils.isEmpty(param)) {
                //根据条件搜索个人作品
                wrapper.eq("user_id", UserHolder.getUserId());
                wrapper.like("title", param);
            } else {
                //查询个人作品
                wrapper.eq("user_id", UserHolder.getUserId());
            }
            Page pages = new Page(page, size);
            Page selectPage = baseMapper.selectPage(pages, wrapper);
            return R.ok(selectPage);
        } else {

            //查询收藏的作品,获取收藏作品id
            wrapper.eq("collect_user_id", UserHolder.getUserId());
            List<ApCollect> apCollects = apCollectMapper.selectList(wrapper);
            List<Integer> articleIds = apCollects.stream().map(ApCollect::getArticleId).collect(Collectors.toList());
            //查询所有文章信息
            List<WmNews> wmNews = baseMapper.selectBatchIds(articleIds);
            int fromIndex = (page - 1) * size;
            int toIndex = Math.min(fromIndex + page, wmNews.size());
            List<WmNews> wmNewsPage = wmNews.subList(fromIndex, toIndex);
            Page pages = new Page(page, size);
            pages.setTotal(wmNews.size())
                    .setRecords(wmNewsPage);
            return R.ok(pages);
        }


    }


}
